//
//  EditBabyGrowEntryView.m
//  BabyHelper
//
//  Created by  thomas on 11-6-25.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "EditBabyGrowEntryView.h"

@implementation EditBabyGrowEntryView
@synthesize processingView,processingLabel;
@synthesize heightLabel,weightLabel,headCirLabel,commentsLabel,heightUnitLabel,weightUnitLabel,headCirUnitLabel,dateLabel;	
@synthesize heightTextField,weightTextField,headCirTextField,commentsTextField,dateButton,picButton,pickedImageView;
@synthesize currentBabyGrowEntry;
@synthesize pickerView,dateFormatter;
@synthesize imgPicker;
@synthesize pickedPhoto;
@synthesize progressSheet;
@synthesize photoChanged;

#define SEND_SEGMENT_CNTRL_WIDTH			130
#define FIRST_SEND_SEGMENT_WIDTH			 66

#define IMAGES_SEGMENT_CONTROLLER_TAG		487
#define SEND_TWIT_SEGMENT_CONTROLLER_TAG	 42

#define PROGRESS_ACTION_SHEET_TAG			214
#define PHOTO_Q_SHEET_TAG					436
#define PROCESSING_PHOTO_SHEET_TAG			3

#define PHOTO_ENABLE_SERVICES_ALERT_TAG		666
#define PHOTO_DO_CANCEL_ALERT_TAG			13

#define K_UI_TYPE_MOVIE						@"public.movie"
#define K_UI_TYPE_IMAGE						@"public.image"


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	self.title = NSLocalizedString(@"Grow Records",@"");
	
	//set default value:
	self.heightLabel.text        = NSLocalizedString(@"Height",@"");
	self.heightUnitLabel.text    = NSLocalizedString(@"cm",@"");
	self.weightLabel.text        = NSLocalizedString(@"Weight",@"");
	self.weightUnitLabel.text    = NSLocalizedString(@"kg",@"");
	self.headCirLabel.text       = NSLocalizedString(@"HeadCir",@"");
	self.headCirUnitLabel.text   = NSLocalizedString(@"cm",@"");
	self.dateLabel.text          = NSLocalizedString(@"Date",@"");
	self.commentsLabel.text      = NSLocalizedString(@"Notes",@"");
	self.commentsTextField.placeholder = NSLocalizedString(@"Please input notes...",@"");
	[self.picButton setTitle:NSLocalizedString(@"Choose Pic...",@"") forState:UIControlStateNormal];	
	self.pickedPhoto			 = nil;
	self.photoChanged			 = false;
	
    [super viewDidLoad];
	UIBarButtonItem *saveItem = [[UIBarButtonItem alloc]
								 initWithTitle:NSLocalizedString(@"Done",@"")
								 style:UIBarButtonItemStyleBordered 
								 target:self
								 action:@selector(toggleSave)		
								 ];
	self.navigationItem.rightBarButtonItem = saveItem;
	[saveItem release];
	
	self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
	[self.dateFormatter setDateFormat:DATE_TIME_FORMAT];
	
	//set background image
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background"]];
	self.view.backgroundColor = [UIColor clearColor];
	//set navigation background color
	self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:navBarRed green:navBarGreen blue:navBarBlue alpha:navBarAlpha];
	
	int kScreenWidth = 320;
	int kScreenHeight = 480;
	self.processingLabel = [[TTActivityLabel alloc] initWithStyle:TTActivityLabelStyleBlackBezel];
	self.processingLabel.text = NSLocalizedString(@"Backing up, don't exit",@"");
	//label.progress = 0.1;
	[self.processingLabel sizeToFit];
	//label.frame = CGRectMake(0, lastView.bottom+10, self.view.width, label.height);
	[self.processingLabel setCenter:CGPointMake(kScreenWidth/2.0, kScreenHeight/2.0-40)]; // I do this because I'm in landscape mode
	[self.view addSubview:self.processingLabel];
	self.processingLabel.hidden = YES;
	
	
	NSDate *date = nil;
	if(self.currentBabyGrowEntry != nil )
	{
		self.weightTextField.text   = [NSString stringWithFormat:@"%0.1f",self.currentBabyGrowEntry.weight];
		self.heightTextField.text   = [NSString stringWithFormat:@"%0.1f",self.currentBabyGrowEntry.height];
		self.headCirTextField.text  = [NSString stringWithFormat:@"%0.1f",self.currentBabyGrowEntry.headCir];
		self.commentsTextField.text = self.currentBabyGrowEntry.comments;
		
		if(![self.currentBabyGrowEntry.photoPath isEqualToString:@"null"])
		{
			NSLog(@"Load Full path is %@",self.currentBabyGrowEntry.photoPath);		
			UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),self.currentBabyGrowEntry.photoPath]];
			self.pickedImageView.image = image;
			self.pickedPhoto = image;
		}		
		
		date = self.currentBabyGrowEntry.timestamp;
		[self.pickerView setDate:date];
	}
	else {
		date = [NSDate date];
		[self.pickerView setDate:date];
	}
	NSString *strTime = [self.dateFormatter stringFromDate:date];
	[self.dateButton setTitle:strTime forState:UIControlStateNormal];
	
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

-(void)viewWillAppear:(BOOL)animated
{
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	[self.pickerView removeFromSuperview];
	self.heightLabel  = nil;
	self.weightLabel  = nil;
	self.headCirLabel = nil;
	self.heightUnitLabel = nil;
	self.weightUnitLabel = nil;
	self.headCirUnitLabel = nil;
	self.dateLabel = nil;
	
	self.heightTextField = nil;
	self.weightTextField = nil;
	self.headCirTextField = nil;
	
	self.dateButton = nil;	
	self.picButton = nil;
	self.pickedImageView = nil;
	
	self.pickerView = nil; 
	self.dateFormatter = nil; 
	
	self.currentBabyGrowEntry = nil;
	self.imgPicker = nil;
	self.pickedPhoto = nil;
}


- (void)dealloc {
	[self.dateFormatter release];  
	[self.currentBabyGrowEntry release];
	[self.pickedPhoto release];
	[self.progressSheet release];
	
    [super dealloc];
}

- (IBAction)dateAction:(id)sender
{
	NSString *strTime = [self.dateFormatter stringFromDate:self.pickerView.date];
	[self.dateButton setTitle:strTime forState:UIControlStateNormal];
}

-(IBAction)backgroundTap:(id)sender{
	[heightTextField resignFirstResponder];
	[weightTextField resignFirstResponder];
	[headCirTextField resignFirstResponder];
	[commentsTextField resignFirstResponder];
	[self SlideDownDatePicker];
}

-(IBAction)toggleSave{
	if([self DataValidation] == YES)
    {
		self.processingLabel.hidden = NO;
		//self.processingView.hidden = NO;
		[self SaveBabyGrowEntry];
		self.processingLabel.hidden = YES;
		//self.processingView.hidden = YES;
		[self.navigationController popViewControllerAnimated:true];		
	}	
}

-(BOOL)DataValidation{
	Dao *dao = [Dao getInstance];
	BabyProfile *babyProfile = [[BabyProfile alloc]init];
	[dao LoadBabyProfile:babyProfile];
	if (babyProfile.Birthday > [[self.pickerView date] timeIntervalSince1970]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"")
														message:NSLocalizedString(@"Input date should not early than birthday",@"")
													   delegate:nil 
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		[babyProfile release];
		return NO;
	}
	[babyProfile release];
	
	if([self.heightTextField.text intValue] < 0 ||
	   [self.weightTextField.text intValue] < 0 ||
	   [self.headCirTextField.text intValue] < 0 )
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"")
														message:NSLocalizedString(@"Invalid input value",@"")
													   delegate:nil 
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		return NO;
	}
	
	if([self.commentsTextField.text length] > 100)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"")
														message:NSLocalizedString(@"Input text too long",@"")
													   delegate:nil 
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		return NO;
	}
	
	
	return YES;
}

-(void)SaveBabyGrowEntry{
	
	Dao *dao = [Dao getInstance];
	PhotoManager *photoManager = [PhotoManager getInstance];

	BabyGrowEntry *entry = [[BabyGrowEntry alloc]init];
	entry.height    = [self.heightTextField.text floatValue];
	entry.weight    = [self.weightTextField.text floatValue];
	entry.headCir   = [self.headCirTextField.text floatValue];
	entry.timestamp = [self.pickerView date];
	entry.comments  = self.commentsTextField.text;
	
	UIImage *thumPhoto = nil;

	if( self.photoChanged == YES)
	{
		//if change the pic, should delete old pic first;
		if(self.currentBabyGrowEntry != nil &&
		   ![self.currentBabyGrowEntry.photoPath isEqualToString:@"null"] &&
		   ![self.currentBabyGrowEntry.thumPath isEqualToString:@"null"])
		{
			remove([[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),self.currentBabyGrowEntry.photoPath] cStringUsingEncoding:NSASCIIStringEncoding]);
			remove([[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),self.currentBabyGrowEntry.thumPath]  cStringUsingEncoding:NSASCIIStringEncoding]);
		}
		
		if( self.pickedPhoto == nil)
		{
			entry.photoPath = @"null";
			entry.thumPath	= @"null";
		}
		else {
			CGSize thumSize    = CGSizeMake(THUM_SIZE,THUM_SIZE);
			//thumPhoto = thumbnailOfImage(self.pickedPhoto,thumSize);
			//thumPhoto = imageByCroppingToRect(self.pickedPhoto,thumSize);
			thumPhoto = imageWithImage(self.pickedPhoto,thumSize);
			
			NSString *thumPath = [NSString stringWithFormat:@"%f_thum.png",[[NSDate date] timeIntervalSince1970]];	
			NSString *fullPath = [NSString stringWithFormat:@"%f_full.png",[[NSDate date] timeIntervalSince1970]];	
			NSLog(@"Thum path is %@ and full path is %@",thumPath,fullPath);
			
			if(writeImage(thumPhoto,thumPath)== NO){
				UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"")
																message:@"failed to write FS"
															   delegate:nil 
													  cancelButtonTitle:@"OK"
													  otherButtonTitles:nil];
				[alert show];
				[alert release];			
			}
			saveImageToLocalFS(self.pickedPhoto,fullPath);
			entry.thumPath  = thumPath;
			entry.photoPath = fullPath;
		}

	}else if(self.photoChanged == NO){
		//if pic not changed keep the old path;
		//if change the pic, should delete old pic first;
		if(self.currentBabyGrowEntry != nil &&
		   ![self.currentBabyGrowEntry.photoPath isEqualToString:@"null"] &&
		   ![self.currentBabyGrowEntry.thumPath isEqualToString:@"null"])
		{
			entry.photoPath = self.currentBabyGrowEntry.photoPath;
			entry.thumPath  = self.currentBabyGrowEntry.thumPath;
		}else {
			entry.photoPath = @"null";
			entry.thumPath	= @"null";
		}
	}
	else{
		entry.photoPath = @"null";
		entry.thumPath	= @"null";
	}
	
	if(self.currentBabyGrowEntry == nil )
	{
		[dao InsertBabyGrowEntry:entry];
		[photoManager InsertThumImageByBabyGrowID:entry.photoID image:thumPhoto];
	}else {
		entry.index   = self.currentBabyGrowEntry.index;
		entry.photoID = self.currentBabyGrowEntry.photoID;
		if (thumPhoto !=nil) {
			[photoManager UpdateThumImageByBabyGrowID:entry.photoID image:thumPhoto];		
		}
		[dao UpdateBabyGrowEntry:entry];
	}
	
	[entry release];	
}


-(IBAction)SlideDownDatePickView:(id)sender
{
	// the date picker has finished sliding downwards, so remove it
	[self SlideDownDatePicker];
}

-(IBAction)toggleDateControl:(id)sender
{
	self.pickerView.date = [self.dateFormatter dateFromString:[self.dateButton currentTitle]];
	// check if our date picker is already on screen
	if (self.pickerView.superview == nil)
	{
		[self.view.window addSubview: self.pickerView];
		
		// size up the picker view to our screen and compute the start/end frame origin for our slide up animation
		//
		// compute the start frame
		CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
		CGSize pickerSize = [self.pickerView sizeThatFits:CGSizeZero];
		CGRect startRect = CGRectMake(0.0,
									  screenRect.origin.y + screenRect.size.height,
									  pickerSize.width, pickerSize.height);
		self.pickerView.frame = startRect;
		
		// compute the end frame
		CGRect pickerRect = CGRectMake(0.0,
									   screenRect.origin.y + screenRect.size.height - pickerSize.height - 0,
									   //screenRect.origin.y + screenRect.size.height - pickerSize.height - 49, //if we want to show the status bar
									   pickerSize.width,
									   pickerSize.height);
		// start the slide up animation
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.3];
		
		// we need to perform some post operations after the animation is complete
		[UIView setAnimationDelegate:self];
		
		self.pickerView.frame = pickerRect;
		
		// shrink the table vertical size to make room for the date picker
		CGRect newFrame = self.view.frame;
		newFrame.size.height -= self.pickerView.frame.size.height;
		self.view.frame = newFrame;
		[UIView commitAnimations];
	}
}

-(void)slideDownDidStop
{
	// the date picker has finished sliding downwards, so remove it
	[self.pickerView removeFromSuperview];
}

-(void)SlideDownDatePicker
{
	CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
	CGRect endFrame = self.pickerView.frame;
	endFrame.origin.y = screenRect.origin.y + screenRect.size.height;
	
	// start the slide down animation
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	
	// we need to perform some post operations after the animation is complete
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(slideDownDidStop)];
	
	self.pickerView.frame = endFrame;
	[UIView commitAnimations];
	
	// grow the table back again in vertical size to make room for the date picker
	CGRect newFrame = self.view.frame;
	newFrame.size.height += self.pickerView.frame.size.height;
	self.view.frame = newFrame;
}

- (void)viewWillDisappear:(BOOL)animated{
	[self SlideDownDatePicker];
}

//Function for choose photo
- (BOOL)mediaIsPicked
{
	return self.pickedPhoto && TRUE;
}

-(IBAction)toggleChoosePic:(id)sender{
	
	BOOL imageAlreadyExists  = [self mediaIsPicked];
	BOOL photoCameraEnabled  = NO;
	BOOL photoLibraryEnabled = NO;
	BOOL movieCameraEnabled  = NO;
	BOOL movieLibraryEnabled = NO;
	
	NSArray *mediaTypes = nil;
	
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
	{
		photoLibraryEnabled = YES;
		if ([[UIImagePickerController class] respondsToSelector:@selector(availableMediaTypesForSourceType:)]) 
		{
			mediaTypes = [self availableMediaTypes:UIImagePickerControllerSourceTypePhotoLibrary];
			movieLibraryEnabled = [mediaTypes indexOfObject:K_UI_TYPE_MOVIE] != NSNotFound;
			photoLibraryEnabled = [mediaTypes indexOfObject:K_UI_TYPE_IMAGE] != NSNotFound;
		}
		
	}
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
	{
		photoCameraEnabled = YES;
		
		if ([[UIImagePickerController class] respondsToSelector:@selector(availableMediaTypesForSourceType:)]) 
		{
			mediaTypes = [self availableMediaTypes:UIImagePickerControllerSourceTypeCamera];
			movieCameraEnabled = [mediaTypes indexOfObject:K_UI_TYPE_MOVIE] != NSNotFound;
			photoCameraEnabled = [mediaTypes indexOfObject:K_UI_TYPE_IMAGE] != NSNotFound;
		}
	}
	
	NSString *buttons[5] = {0};
	int i = 0;
	
	if(photoCameraEnabled)
		buttons[i++] = NSLocalizedString(@"Take Photo", @"");
	//if(movieCameraEnabled)
	//	buttons[i++] = NSLocalizedString(@"Use video camera", @"");
	if(photoLibraryEnabled)
		buttons[i++] = NSLocalizedString(@"User Library", @"");
	//	if(movieLibraryEnabled)
	//		buttons[i++] = NSLocalizedString(@"Use video library", @"");
	if(imageAlreadyExists)
		buttons[i++] = NSLocalizedString(@"Remove Image", @"");
	
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
															 delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"") destructiveButtonTitle:nil
													otherButtonTitles:buttons[0], buttons[1], buttons[2], buttons[3], buttons[4], nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
	actionSheet.tag = PHOTO_Q_SHEET_TAG;
	[actionSheet showInView:self.view];
	[actionSheet release];
}

- (NSArray*)availableMediaTypes:(UIImagePickerControllerSourceType) pickerSourceType
{
	SEL selector = @selector(availableMediaTypesForSourceType:);
	NSMethodSignature *sig = [[UIImagePickerController class] methodSignatureForSelector:selector];
	NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
	[invocation setTarget:[UIImagePickerController class]];
	[invocation setSelector:selector];
	[invocation setArgument:&pickerSourceType atIndex:2];
	[invocation invoke];
	NSArray *mediaTypes = nil;
	[invocation getReturnValue:&mediaTypes];
	return mediaTypes;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(actionSheet.tag == PHOTO_Q_SHEET_TAG)
	{
		if(buttonIndex == actionSheet.cancelButtonIndex)
			return;
		
		if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"Remove Image", @"")])
		{
			[self setImage:nil movie:nil];
			return;
		}
		else if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"Take Photo", @"")])
		{
			imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
			if([imgPicker respondsToSelector:@selector(setMediaTypes:)])
				[imgPicker performSelector:@selector(setMediaTypes:) withObject:[NSArray arrayWithObject:K_UI_TYPE_IMAGE]];
			[self presentModalViewController:imgPicker animated:YES];
			return;
		}
		/*		
		 else if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"User Library", @"");])
		 {
		 imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
		 if([imgPicker respondsToSelector:@selector(setMediaTypes:)])
		 [imgPicker performSelector:@selector(setMediaTypes:) withObject:[NSArray arrayWithObject:K_UI_TYPE_MOVIE]];
		 [self presentModalViewController:imgPicker animated:YES];
		 return;
		 }
		 */
		else if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"User Library", @"")])
		{
			imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
			if([imgPicker respondsToSelector:@selector(setMediaTypes:)])
				[imgPicker performSelector:@selector(setMediaTypes:) withObject:[self availableMediaTypes:UIImagePickerControllerSourceTypePhotoLibrary]];
			[self presentModalViewController:imgPicker animated:YES];
			return;
		}
	}
}

- (void) setImage:(UIImage*)img movie:(NSURL*)url
{
	self.photoChanged = YES;
	self.pickedPhoto = img;
	UIImage* prevImage = nil;
	if(img)
		prevImage = img;
	else if(url)
		prevImage = [UIImage imageNamed:@"MovieIcon.tif"];
	
	//thomas, more work in here
	self.pickedImageView.contentMode = UIViewContentModeScaleAspectFit;
	self.pickedImageView.image = self.pickedPhoto;
	//self.picImage.contentMode = UIViewContentModeScaleAspectFill;
	//self.picImage.contentMode = UIViewContentModeScaleToFill;
	//[self.picButton setImage:thum forState:UIControlStateNormal];
	//[self.picButton setBackgroundImage:thum forState:UIControlStateNormal];
	//CGSize thumSize     = CGSizeMake(60,60);
	//UIImage *thum       = [self thumbnailOfImage:self.pickedPhoto withSize:thumSize];
	//self.picImage.image = [self imageWithImage:thum scaledToSize:thumSize];
	//UIImage *loadedImage  = [UIImage imageWithContentsOfFile:imagePath];
	//self.picImage.image = thum;
	//self.picImage.image = [self thumbnailOfImage:thum withSize:thumSize];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[[picker parentViewController] dismissModalViewControllerAnimated:YES];
	[self.picButton becomeFirstResponder];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
/*	
	if([[info objectForKey:@"UIImagePickerControllerMediaType"] isEqualToString:K_UI_TYPE_IMAGE])
		[self imagePickerController:picker didFinishWithPickingPhoto:[info objectForKey:@"UIImagePickerControllerOriginalImage"] pickingMovie:nil];
	else if([[info objectForKey:@"UIImagePickerControllerMediaType"] isEqualToString:K_UI_TYPE_MOVIE])
		[self imagePickerController:picker didFinishWithPickingPhoto:nil pickingMovie:[info objectForKey:@"UIImagePickerControllerMediaURL"]];
*/ 
	self.photoChanged = true;
	
	[[picker parentViewController] dismissModalViewControllerAnimated:YES];
	
	BOOL startNewUpload = NO;
	
	if(self.pickedPhoto != [info objectForKey:@"UIImagePickerControllerEditedImage"])
	{
		self.photoChanged = true;
		startNewUpload = YES;
		[self setImage:[info objectForKey:@"UIImagePickerControllerEditedImage"] movie:nil];
	}
	
	[self.picButton becomeFirstResponder];
	
	if([info objectForKey:@"UIImagePickerControllerEditedImage"])
	{
		//BOOL needToResize;
		//BOOL needToRotate;
		//isImageNeedToConvert(img, &needToResize, &needToRotate);
		//if(needToResize || needToRotate)
		{
			self.progressSheet = ShowActionSheet(NSLocalizedString(@"Processing image...", @""), self, nil, self.view);
			self.progressSheet.tag = PROCESSING_PHOTO_SHEET_TAG;
		}
	}
	[self startUploadingOfPickedMediaIfNeed];
}

- (void)startUploadingOfPickedMediaIfNeed
{
	if(self.pickedPhoto)
	{
		self.pickedPhoto = imageScaledToSize(self.pickedPhoto, IMAGE_SCALING_SIZE);
		//CGSize thumSize    = CGSizeMake(640,960);
		//CGSize thumSize   = CGSizeMake(320,480);
		//self.pickedPhoto  = imageWithImage(self.pickedPhoto,thumSize);
		
	}
	
	if(self.progressSheet && self.progressSheet.tag == PROCESSING_PHOTO_SHEET_TAG)
	{
		[self.progressSheet dismissWithClickedButtonIndex:-1 animated:YES];
		self.progressSheet = nil;
	}		
}
										

//write picture to photot album
/* 						   
 //UIImageWriteToSavedPhotosAlbum(self.pickedPhoto, self, @selector(image:didFinishSavingWithError:contextInfo:), self);					
 
 ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];  
 // Request to save the image to camera roll  
 [library writeImageToSavedPhotosAlbum:[self.pickedPhoto CGImage] orientation:(ALAssetOrientation)[self.pickedPhoto imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){  
 if (error) {  
 NSLog(@"error");  
 } else {  
 NSLog(@"url %@", assetURL);
 NSLog(@"url %@", [assetURL absoluteString]);
 NSLog(@"url %@", [assetURL relativeString]);
 //return [assetURL absoluteString];			  
 UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:assetURL]];
 NSLog(@"finish", [assetURL relativeString]);
 }  
 }];  
 [library release];	
 */
@end